package com.nexgo.payment.action.transresp;

import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;

import com.nexgo.oaf.apiv3.SdkResult;
import com.nexgo.payment.App;
import com.nexgo.payment.R;
import com.nexgo.payment.aop.annotation.RunOnMainThread;
import com.nexgo.payment.constrant.PreferencesConstants;
import com.nexgo.payment.databases.DataSource;
import com.nexgo.payment.databases.TransRecord;
import com.nexgo.payment.util.PrintHelper;
import com.nexgo.sound.SoundManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * 交易结果P层实现
 *
 * @author 谭忠扬-YuriTam
 * @time 2017年08月14日
 */
public class TransRespPresenter implements TransRespContract.Presenter {
    private Logger mLog = LoggerFactory.getLogger(TransRespPresenter.class.getSimpleName());

    private final SoundManager mSoundManager;
    private TransRespContract.View mView;
    private DataSource mRepository;
    private TransRecord mTransRecord;
    //记录当前打印次数
    private int mPrintTimes = 0;
    private boolean isFirstTimes = true;

    public TransRespPresenter(@NonNull TransRespContract.View view, @NonNull DataSource repository) {
        mView = checkNotNull(view);
        mRepository = checkNotNull(repository);
        view.setPresenter(this);
        mSoundManager = new SoundManager();
    }

    @Override
    public void start() {
        if (isFirstTimes) {
            mSoundManager.play(SoundManager.Type.TRANS_SUCC);
            //获取该条交易记录(即最后一笔)
            mTransRecord = mRepository.getLastSuccessfulTransRecord();
            postMainThread(() -> mView.showTransResp(mTransRecord));
            //开始打印
            if (mTransRecord.getIsSuccess() && "1".equals(mRepository.getParamValue(PreferencesConstants.IS_PRINT_SALES_SLIP))) {
                new Handler(Looper.myLooper()).postDelayed(() -> startPrint(), 300);
            } else {
                postMainThread(() -> mView.showPrintSuccess());
            }
            isFirstTimes = false;
        }
    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        mSoundManager.stop();
    }

    @Override
    public void startPrint() {
        //获取总打印联数
        int totalTimes = Integer.parseInt(mRepository.getParamValue(PreferencesConstants.PRINT_TIMES));
        if (totalTimes == 0 || mPrintTimes == totalTimes) {
            return;
        }
        //初始化打印机
        int result = PrintHelper.printerCfgInit();
        if (result != SdkResult.Success) {
            postMainThread(() -> mView.showPrintInitErr());
            return;
        }
        //判断打印机是否缺纸
        if (PrintHelper.isPaperLack()) {
            postMainThread(() -> mView.showPrintLackPaper());
            return;
        }
        PrintHelper.formPrintTransData(mTransRecord, mPrintTimes, totalTimes, false);
        //开始打印
        postMainThread(() -> mView.setPrintingIndicator(true));
        PrintHelper.startPrint(true, retCode -> {
            postMainThread(() -> mView.setPrintingIndicator(false));
            switch (retCode) {
                case SdkResult.Success:
                    if (mPrintTimes == 0) {
                        mTransRecord.setIsPrinted(true);
                        mRepository.updateTransRecord(mTransRecord);
                    }
                    ++mPrintTimes;
                    if (mPrintTimes < totalTimes) {
                        postMainThread(() -> mView.showConfirmPrintAgain());
                        return;
                    }
                    postMainThread(() -> mView.showPrintSuccess());
                    break;
                case SdkResult.Printer_PaperLack:
                    postMainThread(() -> mView.showPrintLackPaper());
                    break;
                default:
                    postMainThread(() -> mView.showPrintFail(App.sContext.getString(R.string.print_fail)));
                    break;
            }
        });
    }

    @RunOnMainThread
    private void postMainThread(Runnable runnable) {
        if (mView.isActive()) {
            runnable.run();
        }
    }
}
